/**
 * 高智能敌方坦克AI系统
 * 包含路径规划、预测性射击、团队协作等高级算法
 */

// A*寻路算法实现
class PathFinder {
    constructor(gridSize = 20) {
        this.gridSize = gridSize;
        this.grid = null;
        this.width = 0;
        this.height = 0;
    }

    // 初始化网格地图
    initializeGrid(mapWidth, mapHeight, buildings) {
        this.width = Math.ceil(mapWidth / this.gridSize);
        this.height = Math.ceil(mapHeight / this.gridSize);
        this.grid = [];

        // 创建空网格
        for (let x = 0; x < this.width; x++) {
            this.grid[x] = [];
            for (let y = 0; y < this.height; y++) {
                this.grid[x][y] = { walkable: true, cost: 1 };
            }
        }

        // 标记建筑物为不可通行
        for (const building of buildings) {
            const startX = Math.floor(building.position.x / this.gridSize);
            const startY = Math.floor(building.position.y / this.gridSize);
            const endX = Math.ceil((building.position.x + building.size.x) / this.gridSize);
            const endY = Math.ceil((building.position.y + building.size.y) / this.gridSize);

            for (let x = Math.max(0, startX - 1); x <= Math.min(this.width - 1, endX + 1); x++) {
                for (let y = Math.max(0, startY - 1); y <= Math.min(this.height - 1, endY + 1); y++) {
                    if (x >= startX && x < endX && y >= startY && y < endY) {
                        this.grid[x][y].walkable = false;
                    } else {
                        // 建筑物周围增加移动成本
                        this.grid[x][y].cost = 3;
                    }
                }
            }
        }
    }

    // A*寻路算法
    findPath(startPos, endPos) {
        const start = {
            x: Math.floor(startPos.x / this.gridSize),
            y: Math.floor(startPos.y / this.gridSize)
        };
        const end = {
            x: Math.floor(endPos.x / this.gridSize),
            y: Math.floor(endPos.y / this.gridSize)
        };

        if (!this.isValidPosition(start) || !this.isValidPosition(end)) {
            return null;
        }

        const openSet = [start];
        const closedSet = new Set();
        const cameFrom = new Map();
        const gScore = new Map();
        const fScore = new Map();

        gScore.set(this.posKey(start), 0);
        fScore.set(this.posKey(start), this.heuristic(start, end));

        while (openSet.length > 0) {
            // 找到fScore最小的节点
            let current = openSet.reduce((min, pos) => 
                fScore.get(this.posKey(pos)) < fScore.get(this.posKey(min)) ? pos : min
            );

            if (current.x === end.x && current.y === end.y) {
                return this.reconstructPath(cameFrom, current);
            }

            openSet.splice(openSet.indexOf(current), 1);
            closedSet.add(this.posKey(current));

            for (const neighbor of this.getNeighbors(current)) {
                if (closedSet.has(this.posKey(neighbor)) || !this.grid[neighbor.x][neighbor.y].walkable) {
                    continue;
                }

                const tentativeGScore = gScore.get(this.posKey(current)) + this.grid[neighbor.x][neighbor.y].cost;

                if (!openSet.some(pos => pos.x === neighbor.x && pos.y === neighbor.y)) {
                    openSet.push(neighbor);
                } else if (tentativeGScore >= gScore.get(this.posKey(neighbor))) {
                    continue;
                }

                cameFrom.set(this.posKey(neighbor), current);
                gScore.set(this.posKey(neighbor), tentativeGScore);
                fScore.set(this.posKey(neighbor), tentativeGScore + this.heuristic(neighbor, end));
            }
        }

        return null; // 无路径
    }

    posKey(pos) {
        return `${pos.x},${pos.y}`;
    }

    heuristic(a, b) {
        return Math.abs(a.x - b.x) + Math.abs(a.y - b.y);
    }

    getNeighbors(pos) {
        const neighbors = [];
        const directions = [
            {x: 0, y: 1}, {x: 1, y: 0}, {x: 0, y: -1}, {x: -1, y: 0},
            {x: 1, y: 1}, {x: 1, y: -1}, {x: -1, y: 1}, {x: -1, y: -1}
        ];

        for (const dir of directions) {
            const neighbor = {x: pos.x + dir.x, y: pos.y + dir.y};
            if (this.isValidPosition(neighbor)) {
                neighbors.push(neighbor);
            }
        }

        return neighbors;
    }

    isValidPosition(pos) {
        return pos.x >= 0 && pos.x < this.width && pos.y >= 0 && pos.y < this.height;
    }

    reconstructPath(cameFrom, current) {
        const path = [current];
        while (cameFrom.has(this.posKey(current))) {
            current = cameFrom.get(this.posKey(current));
            path.unshift(current);
        }
        
        // 转换回世界坐标
        return path.map(pos => new Vector2D(
            pos.x * this.gridSize + this.gridSize / 2,
            pos.y * this.gridSize + this.gridSize / 2
        ));
    }
}

// 射击预测系统
class ShootingPredictor {
    static predictTargetPosition(target, bulletSpeed, shooterPos) {
        if (!target.velocity || target.velocity.magnitude() === 0) {
            return target.position.clone();
        }

        const distance = shooterPos.distance(target.position);
        const timeToTarget = distance / bulletSpeed;
        
        // 预测目标未来位置
        const futurePos = Vector2D.add(target.position, 
            Vector2D.multiply(target.velocity, timeToTarget));
        
        return futurePos;
    }

    static calculateLeadShot(shooterPos, targetPos, targetVelocity, bulletSpeed) {
        const relativePos = Vector2D.subtract(targetPos, shooterPos);
        const relativeSpeed = targetVelocity.magnitude();
        
        if (relativeSpeed === 0) {
            return relativePos.normalize();
        }

        // 计算拦截角度
        const a = relativeSpeed * relativeSpeed - bulletSpeed * bulletSpeed;
        const b = 2 * relativePos.dot(targetVelocity);
        const c = relativePos.dot(relativePos);

        const discriminant = b * b - 4 * a * c;
        if (discriminant < 0) {
            return relativePos.normalize(); // 无法拦截，直射
        }

        const t = (-b - Math.sqrt(discriminant)) / (2 * a);
        if (t < 0) {
            return relativePos.normalize();
        }

        const interceptPoint = Vector2D.add(targetPos, Vector2D.multiply(targetVelocity, t));
        return Vector2D.subtract(interceptPoint, shooterPos).normalize();
    }
}

// 战术分析器
class TacticalAnalyzer {
    static analyzePlayerBehavior(player, history = []) {
        const patterns = {
            aggressive: 0,
            defensive: 0,
            mobile: 0,
            camping: 0
        };

        if (history.length < 10) return patterns;

        // 分析移动模式
        let totalMovement = 0;
        let directionChanges = 0;
        let avgSpeed = 0;

        for (let i = 1; i < history.length; i++) {
            const movement = history[i].position.distance(history[i-1].position);
            totalMovement += movement;
            avgSpeed += movement;

            if (i > 1) {
                const angle1 = Vector2D.subtract(history[i].position, history[i-1].position).angle();
                const angle2 = Vector2D.subtract(history[i-1].position, history[i-2].position).angle();
                if (Math.abs(angle1 - angle2) > Math.PI / 4) {
                    directionChanges++;
                }
            }
        }

        avgSpeed /= history.length;
        
        // 计算行为特征
        patterns.mobile = Math.min(1, avgSpeed / 5);
        patterns.camping = 1 - patterns.mobile;
        patterns.aggressive = Math.min(1, directionChanges / (history.length / 3));
        patterns.defensive = 1 - patterns.aggressive;

        return patterns;
    }

    static selectOptimalStrategy(distance, playerBehavior, teamStatus) {
        let strategy = 'balanced';
        
        if (distance < 150) {
            if (playerBehavior.aggressive > 0.6) {
                strategy = 'retreat_and_flank';
            } else {
                strategy = 'aggressive_assault';
            }
        } else if (distance < 300) {
            if (playerBehavior.mobile > 0.7) {
                strategy = 'prediction_shot';
            } else {
                strategy = 'advance_and_shoot';
            }
        } else {
            if (teamStatus.allies > 1) {
                strategy = 'coordinate_attack';
            } else {
                strategy = 'long_range_harass';
            }
        }

        return strategy;
    }
}

// 主AI控制器
class TankAI {
    constructor(tank, difficulty = 'hard') {
        this.tank = tank;
        this.difficulty = difficulty;
        this.state = 'patrol';
        this.target = null;
        this.allies = [];
        
        // AI配置
        this.config = this.getDifficultySettings();
        
        // 移动相关
        this.currentPath = null;
        this.pathIndex = 0;
        this.pathFinder = new PathFinder();
        this.moveDirection = new Vector2D(0, 0);
        this.lastPosition = tank.position.clone();
        this.stuckTime = 0;
        
        // 确保坦克有移动方向属性
        if (!this.tank.moveDirection) {
            this.tank.moveDirection = new Vector2D(0, 0);
        }
        
        // 射击相关
        this.lastShotTime = 0;
        this.isAiming = false;
        this.aimingStartTime = 0;
        this.targetAngle = 0;
        
        // 掩体相关
        this.coverPosition = null;
        this.lastCoverSearch = 0;
        
        // 行为分析
        this.playerHistory = [];
        this.lastBehaviorAnalysis = 0;
        this.tacticalAnalysis = {};
        this.currentStrategy = 'balanced';
        
        // 性能优化 - 减少更新频率
        this.updateIntervals = {
            pathfinding: 0,
            behaviorAnalysis: 0,
            teamCommunication: 0,
            strategyCalculation: 0,
            lastMapUpdate: 0
        };
        
        this.updateFrequency = {
            pathfinding: 500,        // 每500ms更新一次路径
            behaviorAnalysis: 2000,  // 每2秒分析一次行为
            teamCommunication: 300,  // 每300ms更新一次通讯
            strategyCalculation: 1000, // 每1秒计算一次策略
            mapUpdate: 5000          // 每5秒更新一次地图
        };
        
        // 异步任务状态
        this.pendingTasks = new Set();
        this.cachedResults = new Map();
        
        // 增强的团队通讯系统
        this.communication = {
            lastUpdate: 0,
            sharedTargets: [],
            lastPlayerSpotting: 0,
            alertRadius: 400,
            lastAlertTime: 0,
            alertCooldown: 3000,
            playerLastKnownPosition: null,
            playerSpottingConfidence: 0,
            teamAlertLevel: 'green',
            isReceivingAlert: false,
            alertSource: null,
            convergenceTarget: null,
            supportRequestTime: 0,
            isSupportRequested: false
        };
        
        // 初始化路径查找器
        this.pathFinder.initializeGrid(window.innerWidth, window.innerHeight, []);
        
        // 初始化视野信息
        this.visionInfo = {
            viewDistance: 400,
            viewAngle: Math.PI / 2,
            turretAngle: this.tank.angle + Math.PI / 2,
            playerInView: false,
            playerDistance: 0,
            playerAngleDiff: 0
        };
        
        // 立即生成一个初始巡逻目标
        this.generateRandomPatrolTarget();
        
        console.log(`🤖 AI初始化完成 - 敌人${this.tank.id || '未知'}, 状态: ${this.state}`);
    }

    getDifficultySettings() {
        const settings = {
            easy: {
                accuracy: 0.3,
                reactionTime: 800,
                predictionAccuracy: 0.1,
                pathfindingUpdate: 1000,
                teamCoordination: 0.2,
                turretSpeed: Math.PI * 1.0, // 慢速转动
                detectionRange: 250
            },
            normal: {
                accuracy: 0.6,
                reactionTime: 500,
                predictionAccuracy: 0.3,
                pathfindingUpdate: 600,
                teamCoordination: 0.5,
                turretSpeed: Math.PI * 1.2, // 中等转动
                detectionRange: 300
            },
            hard: {
                accuracy: 0.8,
                reactionTime: 300,
                predictionAccuracy: 0.7,
                pathfindingUpdate: 400,
                teamCoordination: 0.8,
                turretSpeed: Math.PI * 1.5, // 快速转动
                detectionRange: 350
            },
            nightmare: {
                accuracy: 0.95,
                reactionTime: 100,
                predictionAccuracy: 0.9,
                pathfindingUpdate: 200,
                teamCoordination: 1.0,
                turretSpeed: Math.PI * 2.0, // 极快转动
                detectionRange: 400
            }
        };
        
        return settings[this.difficulty] || settings.hard;
    }

    async update(player, allies, buildings, bullets, deltaTime) {
        if (!this.tank || this.tank.isDead) return;
        
        // 存储建筑数据，确保detectPlayer等方法可以访问
        this.buildings = buildings;
        
        const currentTime = Date.now();
        
        // 异步更新地图（低频率）
        if (currentTime - this.updateIntervals.lastMapUpdate > this.updateFrequency.mapUpdate) {
            this.updateMapAsync(buildings);
            this.updateIntervals.lastMapUpdate = currentTime;
        }
        
        // 记录玩家行为（每帧，但轻量级）
        this.recordPlayerBehavior(player);
        
        // 异步行为分析（低频率）
        if (currentTime - this.updateIntervals.behaviorAnalysis > this.updateFrequency.behaviorAnalysis) {
            this.analyzePlayerBehaviorAsync();
            this.updateIntervals.behaviorAnalysis = currentTime;
        }
        
        // 团队通讯（中频率）
        if (currentTime - this.updateIntervals.teamCommunication > this.updateFrequency.teamCommunication) {
            this.updateAdvancedTeamCommunication(player, allies);
            this.updateIntervals.teamCommunication = currentTime;
        }
        
        // 异步策略计算（低频率）
        if (currentTime - this.updateIntervals.strategyCalculation > this.updateFrequency.strategyCalculation) {
            this.calculateStrategyAsync(player, allies, buildings);
            this.updateIntervals.strategyCalculation = currentTime;
        }
        
        // 执行AI行为（每帧，但基于缓存的结果）
        this.executeAIBehavior(player, allies, buildings, bullets, deltaTime);
        
        // 检查是否被卡住（每帧）
        this.checkIfStuck(deltaTime);
    }

    async updateMapAsync(buildings) {
        if (!window.gameAIManager) return;
        
        try {
            await window.gameAIManager.initAllGrids(
                window.innerWidth, 
                window.innerHeight, 
                buildings.map(b => ({
                    position: { x: b.position.x, y: b.position.y },
                    size: { x: b.size.x, y: b.size.y }
                }))
            );
        } catch (error) {
            console.warn('异步地图更新失败，回退到同步模式:', error);
            this.pathFinder.initializeGrid(window.innerWidth, window.innerHeight, buildings);
        }
    }

    async analyzePlayerBehaviorAsync() {
        if (!window.gameAIManager || this.playerHistory.length < 10) return;
        
        const taskKey = 'behaviorAnalysis_' + this.tank.id;
        if (this.pendingTasks.has(taskKey)) return;
        
        this.pendingTasks.add(taskKey);
        
        try {
            const result = await window.gameAIManager.postTask('analyzePlayerBehavior', {
                history: this.playerHistory.slice(-20).map(h => ({
                    position: { x: h.position.x, y: h.position.y },
                    timestamp: h.timestamp,
                    health: h.health
                })),
                tankId: this.tank.id
            }, 1); // 低优先级
            
            if (result && result.patterns) {
                this.cachedResults.set('playerBehavior', result.patterns);
            }
        } catch (error) {
            console.warn('异步行为分析失败:', error);
        } finally {
            this.pendingTasks.delete(taskKey);
        }
    }

    async calculateStrategyAsync(player, allies, buildings) {
        if (!window.gameAIManager || !player) return;
        
        const taskKey = 'strategyCalculation_' + this.tank.id;
        if (this.pendingTasks.has(taskKey)) return;
        
        this.pendingTasks.add(taskKey);
        
        try {
            const distance = this.tank.position.distance(player.position);
            const playerBehavior = this.cachedResults.get('playerBehavior') || {
                aggressive: 0.5, defensive: 0.5, mobile: 0.5, camping: 0.5
            };
            const teamStatus = {
                allies: this.allies.length,
                averageHealth: this.allies.reduce((sum, ally) => sum + ally.health, this.tank.health) / (this.allies.length + 1)
            };
            
            const result = await window.gameAIManager.postTask('calculateOptimalStrategy', {
                distance,
                playerBehavior,
                teamStatus,
                tankId: this.tank.id
            }, 2); // 中等优先级
            
            if (result && result.strategy) {
                this.currentStrategy = result.strategy;
                this.tacticalAnalysis = { distance, playerBehavior, teamStatus };
            }
        } catch (error) {
            console.warn('异步策略计算失败:', error);
        } finally {
            this.pendingTasks.delete(taskKey);
        }
    }

    async requestPathAsync(startPos, endPos, priority = 0) {
        if (!window.gameAIManager) {
            // 回退到同步路径查找
            return this.pathFinder.findPath(startPos, endPos);
        }
        
        const taskKey = `pathfinding_${this.tank.id}_${Date.now()}`;
        
        try {
            const result = await window.gameAIManager.postTask('findPath', {
                start: { x: startPos.x, y: startPos.y },
                end: { x: endPos.x, y: endPos.y },
                tankId: this.tank.id
            }, priority);
            
            if (result && result.path) {
                return result.path.map(p => new Vector2D(p.x, p.y));
            }
        } catch (error) {
            console.warn('异步路径查找失败，回退到同步模式:', error);
            return this.pathFinder.findPath(startPos, endPos);
        }
        
        return null;
    }

    recordPlayerBehavior(player) {
        if (!player) return;
        
        this.playerHistory.push({
            position: player.position.clone(),
            timestamp: Date.now(),
            health: player.health
        });
        
        // 保持历史记录在合理范围内
        if (this.playerHistory.length > 50) {
            this.playerHistory.shift();
        }
    }

    updateAdvancedTeamCommunication(player, allies) {
        this.allies = allies.filter(ally => !ally.isDead && ally !== this.tank);
        
        // 确保建筑数据可用于视线检测
        // 注意：buildings会在update方法中通过参数传递，但为了确保detectPlayer能访问到，我们需要存储它
        
        const currentTime = Date.now();
        
        // 检测是否发现玩家
        this.detectPlayer(player);
        
        // 更新团队通信
        this.broadcastIntelligence(player);
        this.receiveTeamIntelligence();
        this.updateTeamAlertLevel();
        
        // 处理支援请求
        this.processSupportRequests(player);
    }

    detectPlayer(player) {
        if (!player) return;
        
        const distance = this.tank.position.distance(player.position);
        const currentTime = Date.now();
        
        // 计算玩家相对于坦克的角度
        const playerDirection = Vector2D.subtract(player.position, this.tank.position);
        const playerAngle = playerDirection.angle();
        
        // 坦克炮管方向（坦克角度 + π/2 因为默认朝上）
        const tankTurretAngle = this.tank.angle + Math.PI / 2;
        
        // 计算角度差值，归一化到 [-π, π] 范围
        let angleDiff = playerAngle - tankTurretAngle;
        while (angleDiff > Math.PI) angleDiff -= 2 * Math.PI;
        while (angleDiff < -Math.PI) angleDiff += 2 * Math.PI;
        
        // 视野参数
        const viewDistance = 400; // 视野距离（从200改为400）
        const viewAngle = Math.PI / 2; // 90度视角 (π/2 弧度，从π/4改为π/2)
        
        // 检查是否在视野范围内
        const isInViewDistance = distance <= viewDistance;
        const isInViewAngle = Math.abs(angleDiff) <= viewAngle / 2; // 左右各45度
        
        // 重要修改：传递正确的建筑数据来检测视线遮挡
        const hasLOS = this.hasLineOfSight(player.position, this.buildings || []);
        
        // 只有同时满足距离、角度和视线条件才能发现玩家
        const isPlayerDetected = isInViewDistance && isInViewAngle && hasLOS;
        
        // 存储视野信息用于可视化
        this.visionInfo = {
            viewDistance: viewDistance,
            viewAngle: viewAngle,
            turretAngle: tankTurretAngle,
            playerInView: isPlayerDetected,
            playerDistance: distance,
            playerAngleDiff: angleDiff,
            hasLineOfSight: hasLOS,
            isInViewDistance: isInViewDistance,
            isInViewAngle: isInViewAngle
        };
        
        if (isPlayerDetected) {
            // 更新玩家位置信息
            this.communication.playerLastKnownPosition = player.position.clone();
            this.communication.lastPlayerSpotting = currentTime;
            this.communication.playerSpottingConfidence = Math.min(1.0, 
                this.communication.playerSpottingConfidence + 0.2); // 增加信心值提升速度
            
            // 立即发出警报（移除冷却时间限制）
            this.broadcastPlayerAlert(player);
            this.communication.lastAlertTime = currentTime;
            
            console.log(`🚨 敌人${this.tank.id || '未知'}在视野内发现玩家！距离: ${distance.toFixed()}px, 角度差: ${(angleDiff * 180 / Math.PI).toFixed()}度, 视线通畅: ${hasLOS}`);
            
            // 总是请求支援（更积极的团队协作）
            if (this.shouldRequestSupport(player)) {
                this.requestTeamSupport(player);
            }
        } else {
            // 逐渐降低信心值
            this.communication.playerSpottingConfidence = Math.max(0, 
                this.communication.playerSpottingConfidence - 0.02);
            
            // 如果玩家不在视野内，设置视野信息
            this.visionInfo = {
                viewDistance: viewDistance,
                viewAngle: viewAngle,
                turretAngle: tankTurretAngle,
                playerInView: false,
                playerDistance: distance,
                playerAngleDiff: angleDiff,
                hasLineOfSight: hasLOS,
                isInViewDistance: isInViewDistance,
                isInViewAngle: isInViewAngle
            };
            
            // 调试输出：为什么没有发现玩家
            if (isInViewDistance && isInViewAngle && !hasLOS) {
                console.log(`👁️ 敌人${this.tank.id || '未知'}视野内有玩家但被建筑物遮挡！距离: ${distance.toFixed()}px, 角度差: ${(angleDiff * 180 / Math.PI).toFixed()}度`);
            }
        }
    }

    broadcastPlayerAlert(player) {
        const alertData = {
            type: 'player_spotted',
            playerPosition: player.position.clone(),
            reporterPosition: this.tank.position.clone(),
            timestamp: Date.now(),
            confidence: this.communication.playerSpottingConfidence,
            urgency: this.calculateAlertUrgency(player),
            reporterId: this.tank.id || Math.random().toString(36).substr(2, 9)
        };
        
        // 扩大广播范围，向所有队友广播（移除距离限制）
        let alertsSent = 0;
        for (const ally of this.allies) {
            if (ally.ai) {
                ally.ai.receivePlayerAlert(alertData);
                alertsSent++;
            }
        }
        
        console.log(`📡 警报已发送给${alertsSent}个队友，玩家位置: ${player.position.x.toFixed()}, ${player.position.y.toFixed()}`);
    }

    receivePlayerAlert(alertData) {
        const currentTime = Date.now();
        
        // 处理玩家发现警报
        if (alertData.type === 'player_spotted') {
            // 更新共享的玩家位置信息
            this.communication.playerLastKnownPosition = alertData.playerPosition.clone();
            this.communication.isReceivingAlert = true;
            this.communication.alertSource = alertData.reporterPosition.clone();
            
            // 更积极的响应 - 降低紧急度阈值
            if (alertData.urgency > 0.3) { // 从0.7降低到0.3
                this.communication.teamAlertLevel = 'red';
                this.communication.convergenceTarget = alertData.playerPosition.clone();
                
                // 如果当前在巡逻，立即转为支援模式
                if (this.state === 'patrol') {
                    this.state = 'coordinate';
                    this.currentPath = null;  // 清除当前路径，重新规划
                    console.log(`📡 敌人${this.tank.id}收到高优先级警报！立即前往支援位置`);
                }
            } else {
                this.communication.teamAlertLevel = 'yellow';
                
                // 更积极地前往协助 - 扩大响应距离
                const distanceToAlert = this.tank.position.distance(alertData.playerPosition);
                if (distanceToAlert < 600) { // 从300扩大到600
                    this.communication.convergenceTarget = alertData.playerPosition.clone();
                    if (this.state === 'patrol') {
                        this.state = 'coordinate';
                        this.currentPath = null;
                        console.log(`📻 敌人${this.tank.id}收到警报，前往协助`);
                    }
                }
            }
        }
        
        // 处理支援请求
        else if (alertData.type === 'support_request') {
            const distanceToRequest = this.tank.position.distance(alertData.reporterPosition);
            
            // 更积极的支援响应 - 扩大响应距离
            if (distanceToRequest < 800 && (this.state === 'patrol' || this.state === 'coordinate')) { // 从350扩大到800
                this.communication.convergenceTarget = alertData.supportPosition.clone();
                this.state = 'coordinate';
                this.currentPath = null;
                
                console.log(`🆘 敌人${this.tank.id}响应支援请求！前往: ${alertData.supportPosition.x.toFixed()}, ${alertData.supportPosition.y.toFixed()}`);
            }
        }
    }

    shouldRequestSupport(player) {
        const distance = this.tank.position.distance(player.position);
        const currentTime = Date.now();
        
        // 更积极的支援请求条件
        const needSupport = (
            distance < 300 ||  // 玩家在中等距离内
            this.communication.playerSpottingConfidence > 0.5  // 较低的信心阈值
        );
        
        const canRequestSupport = currentTime - this.communication.supportRequestTime > 3000;  // 减少冷却时间
        
        return needSupport && canRequestSupport && !this.communication.isSupportRequested;
    }

    requestTeamSupport(player) {
        const currentTime = Date.now();
        this.communication.supportRequestTime = currentTime;
        this.communication.isSupportRequested = true;
        
        // 计算最佳支援位置（玩家周围的包围点）
        const supportPositions = this.calculateSupportPositions(player);
        
        const supportData = {
            type: 'support_request',
            reporterPosition: this.tank.position.clone(),
            playerPosition: player.position.clone(),
            supportPosition: supportPositions[0],  // 主要支援位置
            timestamp: currentTime,
            urgency: 0.8,
            reporterId: this.tank.id || Math.random().toString(36).substr(2, 9)
        };
        
        // 向最近的队友发送支援请求
        const nearbyAllies = this.allies.filter(ally => 
            this.tank.position.distance(ally.position) < 400
        ).sort((a, b) => 
            this.tank.position.distance(a.position) - this.tank.position.distance(b.position)
        );
        
        let supportSent = 0;
        for (const ally of nearbyAllies) {
            if (ally.ai && supportSent < 2) {  // 最多请求2个队友支援
                supportData.supportPosition = supportPositions[supportSent] || supportPositions[0];
                ally.ai.receivePlayerAlert(supportData);
                supportSent++;
            }
        }
        
        console.log(`🆘 请求${supportSent}个队友前来支援！`);
        
        // 5秒后重置支援请求状态
        setTimeout(() => {
            this.communication.isSupportRequested = false;
        }, 5000);
    }

    calculateSupportPositions(player) {
        const positions = [];
        const angles = [0, Math.PI * 0.5, Math.PI, Math.PI * 1.5];  // 四个方向
        const distance = 180;  // 支援距离
        
        for (const angle of angles) {
            const pos = new Vector2D(
                player.position.x + Math.cos(angle) * distance,
                player.position.y + Math.sin(angle) * distance
            );
            
            // 确保位置在地图内
            pos.x = Math.max(60, Math.min(window.innerWidth - 60, pos.x));
            pos.y = Math.max(60, Math.min(window.innerHeight - 60, pos.y));
            
            positions.push(pos);
        }
        
        return positions;
    }

    calculateAlertUrgency(player) {
        const distance = this.tank.position.distance(player.position);
        const healthRatio = this.tank.health / (50 + (this.level || 1) * 10);
        
        let urgency = 0.5;  // 基础紧急度
        
        // 距离因素
        if (distance < 150) urgency += 0.3;
        else if (distance < 250) urgency += 0.2;
        
        // 血量因素
        if (healthRatio < 0.5) urgency += 0.2;
        
        // 玩家血量因素（如果能获取到）
        if (player.health && player.health < 50) urgency -= 0.1;
        
        return Math.min(1.0, urgency);
    }

    updateTeamAlertLevel() {
        const currentTime = Date.now();
        
        // 警报级别自动衰减
        if (currentTime - this.communication.lastPlayerSpotting > 10000) {  // 10秒没发现玩家
            if (this.communication.teamAlertLevel === 'red') {
                this.communication.teamAlertLevel = 'yellow';
            } else if (this.communication.teamAlertLevel === 'yellow') {
                this.communication.teamAlertLevel = 'green';
            }
        }
        
        if (currentTime - this.communication.lastPlayerSpotting > 20000) {  // 20秒没发现玩家
            this.communication.teamAlertLevel = 'green';
            this.communication.isReceivingAlert = false;
            this.communication.convergenceTarget = null;
        }
    }

    broadcastIntelligence(player) {
        // 原有的智能共享功能保持不变
        for (const ally of this.allies) {
            if (ally.ai && this.target) {
                ally.ai.communication.sharedTargets.push({
                    target: this.target,
                    priority: this.calculateTargetPriority(this.target),
                    timestamp: Date.now()
                });
            }
        }
    }

    receiveTeamIntelligence() {
        // 处理接收到的情报
        const currentTime = Date.now();
        
        // 清理过期的共享目标
        this.communication.sharedTargets = this.communication.sharedTargets.filter(
            intel => currentTime - intel.timestamp < 15000  // 15秒有效期
        );
    }

    processSupportRequests(player) {
        // 如果收到警报且有集合目标，调整行为
        if (this.communication.convergenceTarget && this.communication.isReceivingAlert) {
            const distanceToTarget = this.tank.position.distance(this.communication.convergenceTarget);
            
            // 如果距离集合点较远，优先前往集合点
            if (distanceToTarget > 100 && (this.state === 'patrol' || this.state === 'coordinate')) {
                this.state = 'coordinate';
                this.currentPath = this.pathFinder.findPath(
                    this.tank.position, 
                    this.communication.convergenceTarget
                );
                this.pathIndex = 0;
            }
        }
    }

    executeAIBehavior(player, allies, buildings, bullets, deltaTime) {
        if (!player) {
            this.state = 'patrol';
            return;
        }

        // 状态机逻辑
        switch (this.state) {
            case 'patrol':
                this.executePatrol(player, buildings);
                break;
            case 'engage':
                this.executeEngage(player, buildings, bullets);
                break;
            case 'flank':
                this.executeFlank(player, buildings);
                break;
            case 'retreat':
                this.executeRetreat(player, buildings);
                break;
            case 'cover':
                this.executeCover(player, buildings);
                break;
            case 'coordinate':
                this.executeCoordinate(player, allies, buildings);
                break;
        }

        // 先更新移动
        this.updateMovement(deltaTime);
        
        // 然后更新射击（可能会暂时调整角度）
        this.updateShooting(player, buildings, bullets);
    }

    async executePatrol(player, buildings) {
        // 只有在视野范围内发现玩家才进入交战状态
        if (this.visionInfo && this.visionInfo.playerInView) {
            this.target = player;
            this.state = 'engage';
            console.log(`🎯 敌人${this.tank.id || '未知'}从巡逻转为交战状态`);
            return;
        }
        
        // 确保AI继续巡逻移动
        if (!this.currentPath || this.pathIndex >= this.currentPath.length) {
            await this.generatePatrolPathAsync(buildings);
        }
        
        // 如果还是没有路径，生成一个随机移动目标
        if (!this.currentPath || this.currentPath.length === 0) {
            this.generateRandomPatrolTarget();
        }
    }

    generateRandomPatrolTarget() {
        // 生成随机巡逻目标，确保AI不会卡住
        const margin = 100;
        const targetX = margin + Math.random() * (window.innerWidth - margin * 2);
        const targetY = margin + Math.random() * (window.innerHeight - margin * 2);
        
        this.currentPath = [
            this.tank.position.clone(),
            new Vector2D(targetX, targetY)
        ];
        this.pathIndex = 0;
        
        console.log(`🚶 敌人${this.tank.id || '未知'}生成随机巡逻目标: ${targetX.toFixed()}, ${targetY.toFixed()}`);
    }

    async generatePatrolPathAsync(buildings) {
        const patrolPoints = this.generatePatrolPoints(buildings);
        if (patrolPoints.length > 0) {
            const nearestPoint = patrolPoints.reduce((nearest, point) => 
                this.tank.position.distance(point) < this.tank.position.distance(nearest) ? point : nearest
            );
            
            // 异步路径查找
            const currentTime = Date.now();
            if (currentTime - this.updateIntervals.pathfinding > this.updateFrequency.pathfinding) {
                this.currentPath = await this.requestPathAsync(this.tank.position, nearestPoint, 0);
                this.pathIndex = 0;
                this.updateIntervals.pathfinding = currentTime;
            }
        }
    }

    async planDirectAttack(player, buildings) {
        this.currentPath = await this.requestPathAsync(this.tank.position, player.position, 3);
        this.pathIndex = 0;
    }

    async planAdvanceAndShoot(player, buildings) {
        const direction = Vector2D.subtract(player.position, this.tank.position).normalize();
        const targetDistance = 180;
        const targetPos = Vector2D.add(this.tank.position, Vector2D.multiply(direction, targetDistance));
        
        this.currentPath = await this.requestPathAsync(this.tank.position, targetPos, 2);
        this.pathIndex = 0;
    }

    async planFlankingRoute(player, buildings) {
        const playerPos = player.position;
        const direction = Vector2D.subtract(playerPos, this.tank.position).normalize();
        
        const flankDirection = new Vector2D(-direction.y, direction.x);
        const flankDistance = 200;
        
        let flankPos = Vector2D.add(playerPos, Vector2D.multiply(flankDirection, flankDistance));
        
        flankPos.x = Math.max(50, Math.min(window.innerWidth - 50, flankPos.x));
        flankPos.y = Math.max(50, Math.min(window.innerHeight - 50, flankPos.y));
        
        this.currentPath = await this.requestPathAsync(this.tank.position, flankPos, 2);
        this.pathIndex = 0;
    }

    async planRetreatRoute(player, buildings) {
        this.findOptimalCover(player, buildings);
        if (this.coverPosition) {
            this.currentPath = await this.requestPathAsync(this.tank.position, this.coverPosition, 3);
            this.pathIndex = 0;
        } else {
            const direction = Vector2D.subtract(this.tank.position, player.position).normalize();
            const retreatPos = Vector2D.add(this.tank.position, Vector2D.multiply(direction, 300));
            this.currentPath = await this.requestPathAsync(this.tank.position, retreatPos, 3);
            this.pathIndex = 0;
        }
    }

    generatePatrolPoints(buildings) {
        const points = [];
        const margin = 100;
        
        // 生成一些战略控制点
        points.push(
            new Vector2D(margin, margin),
            new Vector2D(window.innerWidth - margin, margin),
            new Vector2D(window.innerWidth - margin, window.innerHeight - margin),
            new Vector2D(margin, window.innerHeight - margin),
            new Vector2D(window.innerWidth / 2, window.innerHeight / 2)
        );
        
        return points;
    }

    // 射击相关方法
    updateShooting(player, buildings, bullets) {
        if (!player || Date.now() - this.lastShotTime < this.tank.shootCooldown) {
            this.isAiming = false; // 不在射击冷却时，不算瞄准
            return;
        }
        
        // 只有在视野范围内才能射击
        if (!this.visionInfo || !this.visionInfo.playerInView) {
            this.isAiming = false;
            return;
        }
        
        const distance = this.tank.position.distance(player.position);
        if (distance > 350) {
            this.isAiming = false;
            return; // 超出射程
        }
        
        // 开始瞄准
        this.isAiming = true;
        
        // 计算射击方向
        let targetPos = player.position.clone();
        
        // 预测性射击
        if (this.getDifficultySettings().predictionAccuracy > Math.random()) {
            const bulletSpeed = 400;
            targetPos = ShootingPredictor.predictTargetPosition(
                { position: player.position, velocity: this.estimatePlayerVelocity() },
                bulletSpeed,
                this.tank.position
            );
        }
        
        // 射击精度调整
        const accuracy = this.getDifficultySettings().accuracy;
        const spread = (1 - accuracy) * Math.PI * 0.2; // 最大扩散角度
        const randomSpread = (Math.random() - 0.5) * spread;
        
        const direction = Vector2D.subtract(targetPos, this.tank.position).normalize();
        const targetAngle = direction.angle() + randomSpread;
        
        // 计算当前炮塔角度与目标角度的差值
        const currentTurretAngle = this.tank.angle + Math.PI / 2; // 当前炮塔朝向
        let angleDiff = targetAngle - currentTurretAngle;
        
        // 标准化角度差值到 [-π, π] 范围
        while (angleDiff > Math.PI) angleDiff -= 2 * Math.PI;
        while (angleDiff < -Math.PI) angleDiff += 2 * Math.PI;
        
        // 设置转动速度（根据AI难度调整）
        const turretRotationSpeed = this.getDifficultySettings().turretSpeed || (Math.PI * 1.5); // 弧度/秒
        const maxTurnPerFrame = turretRotationSpeed * (1/60); // 假设60FPS
        
        // 检查是否需要转动炮塔
        if (Math.abs(angleDiff) > 0.1) { // 允许小误差
            // 需要转动炮塔，不能射击
            let turnAmount = Math.sign(angleDiff) * Math.min(Math.abs(angleDiff), maxTurnPerFrame);
            
            // 如果正在移动，稍微降低转动速度
            if (this.tank.moveDirection && this.tank.moveDirection.magnitude() > 0) {
                turnAmount *= 0.7; // 移动时转动速度降低30%
            }
            
            // 更新坦克角度（炮塔转动）
            this.tank.angle += turnAmount;
            
            // 标准化角度
            while (this.tank.angle > Math.PI) this.tank.angle -= 2 * Math.PI;
            while (this.tank.angle < -Math.PI) this.tank.angle += 2 * Math.PI;
            
            return; // 炮塔还在转动，不能射击
        }
        
        // 炮塔已对准目标，可以射击
        this.isAiming = false; // 射击后结束瞄准状态
        this.shoot(targetAngle);
    }

    estimatePlayerVelocity() {
        if (this.playerHistory.length < 2) return new Vector2D(0, 0);
        
        const recent = this.playerHistory.slice(-3);
        const velocities = [];
        
        for (let i = 1; i < recent.length; i++) {
            const dt = (recent[i].timestamp - recent[i-1].timestamp) / 1000;
            if (dt > 0) {
                const velocity = Vector2D.subtract(recent[i].position, recent[i-1].position).divide(dt);
                velocities.push(velocity);
            }
        }
        
        if (velocities.length === 0) return new Vector2D(0, 0);
        
        // 平均速度
        const avgVelocity = velocities.reduce((sum, vel) => Vector2D.add(sum, vel), new Vector2D(0, 0));
        return avgVelocity.divide(velocities.length);
    }

    shoot(angle) {
        if (this.onShoot) {
            this.onShoot(angle);
            this.lastShotTime = Date.now();
        }
    }

    // 实用方法
    hasLineOfSight(targetPos, buildings) {
        return CollisionSystem.checkLineOfSight(this.tank.position, targetPos, buildings);
    }

    hasFlankingAdvantage(player) {
        const angle = Vector2D.subtract(this.tank.position, player.position).angle();
        const playerAngle = player.angle || 0;
        const angleDiff = Math.abs(angle - playerAngle);
        return angleDiff > Math.PI / 2; // 在玩家侧面或后方
    }

    findOptimalCover(player, buildings) {
        let bestCover = null;
        let bestScore = -1;
        
        for (const building of buildings) {
            const coverPos = this.findCoverPosition(building, player.position);
            if (coverPos) {
                const score = this.evaluateCoverPosition(coverPos, player.position, building);
                if (score > bestScore) {
                    bestScore = score;
                    bestCover = coverPos;
                }
            }
        }
        
        this.coverPosition = bestCover;
    }

    findCoverPosition(building, playerPos) {
        // 在建筑物后方寻找掩体位置
        const direction = Vector2D.subtract(building.position, playerPos).normalize();
        const offset = Vector2D.multiply(direction, building.size.x / 2 + 30);
        return Vector2D.add(building.position, offset);
    }

    evaluateCoverPosition(coverPos, playerPos, building) {
        const distance = this.tank.position.distance(coverPos);
        const protection = building.size.x + building.size.y; // 掩体大小
        const playerDistance = coverPos.distance(playerPos);
        
        // 评分：距离近、掩体大、与玩家距离适中
        return protection / distance + Math.min(200, playerDistance) / 200;
    }

    executeCoordinate(player, allies, buildings) {
        // 增强的团队协作攻击
        if (this.communication.convergenceTarget) {
            // 如果有特定的集合目标，前往该位置
            const distance = this.tank.position.distance(this.communication.convergenceTarget);
            
            if (distance > 80) { // 减少到达距离要求，从50减到80
                // 还未到达集合点，继续前进
                if (!this.currentPath || this.pathIndex >= this.currentPath.length) {
                    // 使用异步路径查找
                    this.requestPathAsync(this.tank.position, this.communication.convergenceTarget, 3)
                        .then(path => {
                            if (path) {
                                this.currentPath = path;
                                this.pathIndex = 0;
                                console.log(`🎯 敌人${this.tank.id}规划前往集合点的路径`);
                            } else {
                                // 如果无法找到路径，直接前往
                                this.currentPath = [this.tank.position.clone(), this.communication.convergenceTarget.clone()];
                                this.pathIndex = 0;
                                console.log(`🎯 敌人${this.tank.id}直接前往集合点`);
                            }
                        })
                        .catch(error => {
                            console.warn('路径规划失败，使用直线路径:', error);
                            this.currentPath = [this.tank.position.clone(), this.communication.convergenceTarget.clone()];
                            this.pathIndex = 0;
                        });
                }
            } else {
                // 已到达集合点，开始协同攻击
                if (player) {
                    console.log(`✅ 敌人${this.tank.id}到达集合点，开始协同攻击`);
                    this.coordinateTeamAttack(player, allies, buildings);
                }
            }
        } else {
            // 没有集合目标，执行默认的团队协作
            if (player) {
                this.coordinateTeamAttack(player, allies, buildings);
            } else {
                // 没有玩家目标，切换回巡逻
                this.state = 'patrol';
                this.currentPath = null;
            }
        }
    }

    coordinateTeamAttack(player, allies, buildings) {
        // 简化的团队协作：分配不同的攻击角度
        const aliveAllies = this.allies.filter(ally => !ally.isDead);
        if (aliveAllies.length === 0) {
            // 没有队友，直接攻击
            this.state = 'engage';
            this.target = player;
            return;
        }
        
        // 计算包围位置
        const angleStep = (Math.PI * 2) / (aliveAllies.length + 1);
        const myIndex = aliveAllies.findIndex(ally => ally === this.tank);
        const targetAngle = angleStep * (myIndex + 1);
        
        const attackDistance = 250; // 适中的攻击距离
        const attackPos = new Vector2D(
            player.position.x + Math.cos(targetAngle) * attackDistance,
            player.position.y + Math.sin(targetAngle) * attackDistance
        );
        
        // 确保攻击位置在地图内
        attackPos.x = Math.max(60, Math.min(window.innerWidth - 60, attackPos.x));
        attackPos.y = Math.max(60, Math.min(window.innerHeight - 60, attackPos.y));
        
        // 前往攻击位置
        this.requestPathAsync(this.tank.position, attackPos, 3)
            .then(path => {
                if (path) {
                    this.currentPath = path;
                    this.pathIndex = 0;
                    console.log(`⚔️ 敌人${this.tank.id}前往包围位置 (角度: ${(targetAngle * 180 / Math.PI).toFixed()}度)`);
                }
            })
            .catch(error => {
                console.warn('包围路径规划失败:', error);
                this.currentPath = [this.tank.position.clone(), attackPos];
                this.pathIndex = 0;
            });
    }

    updateMovement(deltaTime) {
        if (!this.currentPath || this.pathIndex >= this.currentPath.length) {
            // 没有路径时，停止移动但不清除移动方向
            this.tank.moveDirection = new Vector2D(0, 0);
            return;
        }
        
        const target = this.currentPath[this.pathIndex];
        const direction = Vector2D.subtract(target, this.tank.position);
        const distance = direction.magnitude();
        
        if (distance < 20) {
            this.pathIndex++;
            if (this.pathIndex >= this.currentPath.length) {
                // 路径完成，停止移动
                this.tank.moveDirection = new Vector2D(0, 0);
                console.log(`✅ 敌人${this.tank.id || '未知'}到达目标位置`);
            }
            return;
        }
        
        // 设置坦克移动方向
        this.tank.moveDirection = direction.normalize();
        
        // 注意：这里不再自动设置坦克角度
        // 坦克角度现在专门用于炮塔朝向，由射击系统控制
        // 如果没有在射击，可以让炮塔跟随移动方向
        if (!this.isAiming && this.tank.moveDirection.magnitude() > 0) {
            // 没有瞄准时，炮塔可以跟随移动方向，但速度较慢
            const moveAngle = this.tank.moveDirection.angle() - Math.PI / 2;
            let angleDiff = moveAngle - this.tank.angle;
            
            // 标准化角度差值
            while (angleDiff > Math.PI) angleDiff -= 2 * Math.PI;
            while (angleDiff < -Math.PI) angleDiff += 2 * Math.PI;
            
            // 缓慢调整炮塔朝向移动方向
            const maxTurnPerFrame = (Math.PI * 0.8) * (1/60); // 比射击转动慢一些
            if (Math.abs(angleDiff) > 0.1) {
                const turnAmount = Math.sign(angleDiff) * Math.min(Math.abs(angleDiff), maxTurnPerFrame);
                this.tank.angle += turnAmount;
                
                // 标准化角度
                while (this.tank.angle > Math.PI) this.tank.angle -= 2 * Math.PI;
                while (this.tank.angle < -Math.PI) this.tank.angle += 2 * Math.PI;
            }
        }
        
        // 确保视野信息跟着炮塔角度更新
        if (this.visionInfo) {
            this.visionInfo.turretAngle = this.tank.angle + Math.PI / 2;
        }
    }

    checkIfStuck(deltaTime) {
        const movement = this.tank.position.distance(this.lastPosition);
        
        if (movement < 5) {
            this.stuckTime += deltaTime * 1000;
            
            if (this.stuckTime > 2000) {
                // 被卡住，重新规划路径
                this.currentPath = null;
                this.pathIndex = 0;
                this.stuckTime = 0;
            }
        } else {
            this.stuckTime = 0;
        }
        
        this.lastPosition = this.tank.position.clone();
    }

    calculateTargetPriority(target) {
        if (!target) return 0;
        
        const distance = this.tank.position.distance(target.position);
        const healthRatio = target.health / 100;
        const threat = this.assessThreatLevel(target);
        
        // 距离近、血量低、威胁高的目标优先级更高
        return threat * (1 - healthRatio) * Math.max(0, 1 - distance / 500);
    }

    assessThreatLevel(target) {
        // 简化的威胁评估
        if (target.health > 80) return 0.8;
        if (target.health > 50) return 0.6;
        return 0.4;
    }

    planBalancedEngagement(player, buildings) {
        // 默认的平衡交战策略
        const distance = this.tank.position.distance(player.position);
        
        if (distance > 250) {
            // 距离较远，接近玩家
            this.planAdvanceAndShoot(player, buildings);
        } else if (distance < 120) {
            // 距离太近，撤退一点
            const direction = Vector2D.subtract(this.tank.position, player.position).normalize();
            const retreatPos = Vector2D.add(this.tank.position, Vector2D.multiply(direction, 100));
            
            // 确保撤退位置在地图内
            retreatPos.x = Math.max(80, Math.min(window.innerWidth - 80, retreatPos.x));
            retreatPos.y = Math.max(80, Math.min(window.innerHeight - 80, retreatPos.y));
            
            this.currentPath = this.pathFinder.findPath(this.tank.position, retreatPos);
            this.pathIndex = 0;
        } else {
            // 距离适中，停止移动专心射击
            this.currentPath = null;
            this.tank.moveDirection = new Vector2D(0, 0);
        }
    }

    executeEngage(player, buildings, bullets) {
        // 如果玩家不在视野内，切换回巡逻状态
        if (!this.visionInfo || !this.visionInfo.playerInView) {
            this.state = 'patrol';
            this.target = null;
            this.currentPath = null; // 清除当前路径，重新规划
            console.log(`🔍 敌人${this.tank.id || '未知'}失去玩家视野，切换回巡逻状态`);
            return;
        }
        
        const distance = this.tank.position.distance(player.position);
        const playerBehavior = this.cachedResults.get('playerBehavior') || {
            aggressive: 0.5, defensive: 0.5, mobile: 0.5, camping: 0.5
        };
        
        // 根据当前策略执行不同的交战行为
        switch (this.currentStrategy) {
            case 'aggressive_assault':
                this.planDirectAttack(player, buildings);
                break;
            case 'retreat_and_flank':
                this.state = 'flank';
                break;
            case 'advance_and_shoot':
                this.planAdvanceAndShoot(player, buildings);
                break;
            case 'prediction_shot':
                if (distance > 150) {
                    this.planAdvanceAndShoot(player, buildings);
                } else {
                    this.currentPath = null; // 停止移动，专心射击
                }
                break;
            case 'coordinate_attack':
                this.state = 'coordinate';
                break;
            case 'long_range_harass':
                if (distance < 300) {
                    this.planAdvanceAndShoot(player, buildings);
                }
                break;
            default:
                this.planBalancedEngagement(player, buildings);
                break;
        }
    }
}

// 导出AI系统
window.TankAI = TankAI;
window.PathFinder = PathFinder;
window.ShootingPredictor = ShootingPredictor;
window.TacticalAnalyzer = TacticalAnalyzer; 